package cn.mujiankeji.mbrowser.数据.数据库

import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.Delete
import androidx.room.Query
import kotlinx.coroutines.flow.Flow

@Entity
data class DBSearchHistory(
    @PrimaryKey(autoGenerate = true) val id: Long = 0,

    @ColumnInfo(name = "key", defaultValue = "")
    var 关键词 : String = "",

    @ColumnInfo(name = "time", defaultValue = "0")
    var 时间 : Long = 0L,

    @ColumnInfo(name = "id_search_engine", defaultValue = "NULL")
    var 搜索引擎 : Long? = null // 搜索时使用的搜索引擎
)

@Dao
interface DaoSearchHistory{


    @Query("SELECT * FROM DBSearchHistory ORDER BY time DESC")
    fun 获取所有搜索记录(): Flow<List<DBSearchHistory>>

    @Query("SELECT * FROM DBSearchHistory WHERE `key` LIKE :keyword ORDER BY time DESC")
    fun 根据关键词搜索记录(keyword: String): Flow<List<DBSearchHistory>>

    @Query("SELECT * FROM DBSearchHistory WHERE time >= :startTime AND time <= :endTime ORDER BY time DESC")
    fun 获取指定时间段搜索记录(startTime: Long, endTime: Long): Flow<List<DBSearchHistory>>

    @Delete
    suspend fun 删除单条搜索记录(搜索记录: DBSearchHistory)

    @Query("DELETE FROM DBSearchHistory WHERE `key` = :keyword")
    suspend fun 删除指定关键词的搜索记录(keyword: String)

    @Query("DELETE FROM DBSearchHistory WHERE time < :beforeTime")
    suspend fun 删除指定时间之前的搜索记录(beforeTime: Long)

    @Query("DELETE FROM DBSearchHistory")
    suspend fun 清空所有搜索记录()

    // 如果需要根据搜索引擎ID查询
    @Query("SELECT * FROM DBSearchHistory WHERE id_search_engine = :engineId ORDER BY time DESC")
    fun 获取指定搜索引擎的搜索记录(engineId: Long): Flow<List<DBSearchHistory>>

    // 获取最近N条搜索记录
    @Query("SELECT * FROM DBSearchHistory ORDER BY time DESC LIMIT :count")
    fun 获取最近搜索记录(count: Int): Flow<List<DBSearchHistory>>

    // 获取不重复的关键词列表，按时间倒序
    @Query("SELECT `key` FROM DBSearchHistory GROUP BY `key` ORDER BY MAX(time) DESC")
    fun 获取不重复的关键词(): Flow<List<String>>

    @Query("SELECT `key` FROM DBSearchHistory WHERE `key` LIKE :prefix GROUP BY `key` ORDER BY MAX(time) DESC LIMIT :limit")
    fun 获取关键词建议(prefix: String, limit: Int): Flow<List<String>>
}